package top.seekincs.controller;

import org.springframework.web.bind.annotation.*;
import top.seekincs.client.AlumniSchoolClient;
import top.seekincs.entity.AlumniUserEntity;
import top.seekincs.service.AlumniUserService;
import top.seekincs.vo.AlumniUserVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/user")
public class AlumniUserController {

    final AlumniUserService alumniUserService;
    final AlumniSchoolClient alumniSchoolClient;

    public AlumniUserController(AlumniUserService alumniUserService, AlumniSchoolClient alumniSchoolClient) {
        this.alumniUserService = alumniUserService;
        this.alumniSchoolClient = alumniSchoolClient;
    }

    @PostMapping("/add")
    public AlumniUserEntity register(@RequestParam String username,
                                     @RequestParam String password) {
        if (Objects.isNull(username) || Objects.isNull(password)) {
            return null;
        }
        return alumniUserService.addUser(username, password);
    }

    @GetMapping("/login")
    public AlumniUserEntity login(@RequestParam String username,
                                  @RequestParam String password) {
        AlumniUserEntity userEntity = alumniUserService.userExists(username, password);
        if (userEntity == null) {
            return AlumniUserEntity.builder()
                    .id(0)
                    .build();
        }
        return userEntity;
    }

    @GetMapping("/update")
    public AlumniUserEntity updateUser(AlumniUserVo alumniUserVo) {
        System.out.println(alumniUserVo);
        if (Objects.isNull(alumniUserVo)) {
            return null;
        }
        return alumniUserService.updateUser(
                AlumniUserEntity.builder()
                        .username(alumniUserVo.getUsername())
                        .password(alumniUserVo.getPassword())
                        .address(alumniUserVo.getAddress())
                        .email(alumniUserVo.getEmail())
                        .gender(alumniUserVo.getGender())
                        .profession(alumniUserVo.getProfession())
                        .grade(alumniUserVo.getGrade())
                        .phone(alumniUserVo.getPhone())
                        // 调用 Eureka-Client-School 微服务通过学校名获取学校ID
                        .schoolId(alumniSchoolClient.getSchoolIdByName(alumniUserVo.getSchool()))
                        .build()
        );
    }

    @GetMapping("/all-alumni")
    public List<AlumniUserEntity> findAllAlumniBySchoolId(@RequestParam String username,
                                                          @RequestParam String password) {
        if (username == null || password == null) {
            return new ArrayList<>();
        }
        return alumniUserService.findAllAlumni(username, password);
    }
}
